/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xmlasm.bo;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import utils.XMLUtils;
import xmlasm.dao.UserDAO;
import xmlasm.dto.Users;
import xmlasm.dto.User;
import xmlasm.sync.FilePathHolder;

/**
 *
 * @author Hoang
 */
public class UserBO {

    public static void loadUsersAndMarshall() {
        Users users = UserDAO.getAllUsers();
        //Marshall xuống file xml
        XMLUtils.writeObjectToXML(FilePathHolder.getInstance().getUserXMLPath(), users);
    }

    //Neu trung username thi tra ra true
    public static boolean checkDuplicateUsername(String username, Node node) {
        if (node == null) {
            return false;
        }

        if (node.getNodeName().equals("user")) {
            NodeList userChildren = node.getChildNodes();
            for (int i = 0; i < userChildren.getLength(); i++) {
                Node temp1 = userChildren.item(i);
                if (temp1.getNodeName().equals("username")) {
                    String usernameTemp = temp1.getTextContent().trim().toUpperCase();
                    if (usernameTemp.equals(username.toUpperCase())) {
                        return true;
                    }
                }
            }
        }
        NodeList childNodes = node.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            boolean result = checkDuplicateUsername(username, childNodes.item(i));
            if (result == true) {
                return result;
            }
        }
        return false;
    }

    //Neu trung email thi tra ra true
    public static boolean checkDuplicateEmail(String email, Node node) {
        if (node == null) {
            return false;
        }

        if (node.getNodeName().equals("user")) {
            NodeList userChildren = node.getChildNodes();
            for (int i = 0; i < userChildren.getLength(); i++) {
                Node temp1 = userChildren.item(i);
                if (temp1.getNodeName().equals("email")) {
                    String emailTemp = temp1.getTextContent().trim().toUpperCase();
                    if (emailTemp.equals(email.toUpperCase())) {
                        return true;
                    }
                }
            }
        }
        NodeList childNodes = node.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            boolean result = checkDuplicateEmail(email, childNodes.item(i));
            if (result) {
                return result;
            }
        }
        return false;
    }

    public static void insertUserToXML(User user) {
        Users users = (Users) XMLUtils.getObjectFromXML(
                FilePathHolder.getInstance().getUserXMLPath(), Users.class);
        users.getUser().add(user);
        XMLUtils.writeObjectToXML(
                FilePathHolder.getInstance().getUserXMLPath(), users);
    }

    public static void updateInfoToXML(User user) {
        Users users = (Users) XMLUtils.getObjectFromXML(
                FilePathHolder.getInstance().getUserXMLPath(), Users.class);
        for (User temp : users.getUser()) {
            if (temp.getUserId() == user.getUserId()) {
                temp.setFullName(user.getFullName());
                temp.setEmail(user.getEmail());
                temp.setPassword(user.getPassword());
            }
        }
        XMLUtils.writeObjectToXML(
                FilePathHolder.getInstance().getUserXMLPath(), users);
    }

    public static void setActivation(int userId, boolean status) {
        Users users = (Users) XMLUtils.getObjectFromXML(
                FilePathHolder.getInstance().getUserXMLPath(), Users.class);
        for (User user : users.getUser()) {
            if (user.getUserId() == userId) {
                user.setIsActive(status);
            }
        }
        XMLUtils.writeObjectToXML(
                FilePathHolder.getInstance().getUserXMLPath(), users);
    }

    public static void setPermission(int userId, boolean status) {
        Users users = (Users) XMLUtils.getObjectFromXML(
                FilePathHolder.getInstance().getUserXMLPath(), Users.class);
        for (User user : users.getUser()) {
            if (user.getUserId() == userId) {
                user.setIsAdmin(status);
            }
        }
        XMLUtils.writeObjectToXML(
                FilePathHolder.getInstance().getUserXMLPath(), users);
    }

    private static boolean checkIsActive(int userId, Node node) {
        if (node == null) {
            return false;
        }

        if (node.getNodeName().equals("user")) {
            boolean result = true;
            NodeList userChildren = node.getChildNodes();
            boolean isCurrentUserId = false;
            for (int i = 0; i < userChildren.getLength(); i++) {
                Node temp1 = userChildren.item(i);
                if (temp1.getNodeName().equals("userId")) {
                    int userIdTemp = Integer.parseInt(temp1.getTextContent().trim());
                    if (userIdTemp == userId) {
                        isCurrentUserId = true;
                    }
                }
                if (isCurrentUserId && temp1.getNodeName().equals("isActive")) {
                    boolean actStatus = Boolean.parseBoolean(temp1.getTextContent().trim());
                    if (actStatus == false) {
                        result = false;
                    }
                }
            }
            if (result == false) {
                return result;
            }
        }
        NodeList childNodes = node.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            boolean result = checkIsActive(userId, childNodes.item(i));
            if (result == false) {
                return result;
            }
        }
        return true;
    }

    public static boolean checkIsActive(int userId) {
        try {
            String userFilePath = FilePathHolder.getInstance().getUserXMLPath();
            Document doc = XMLUtils.parseDom(userFilePath);
            return checkIsActive(userId, doc);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(UserBO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(UserBO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(UserBO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }

    private static boolean checkIsAdmin(int userId, Node node) {
        if (node == null) {
            return false;
        }

        if (node.getNodeName().equals("user")) {
            boolean result = true;
            NodeList userChildren = node.getChildNodes();
            boolean isCurrentUserId = false;
            for (int i = 0; i < userChildren.getLength(); i++) {
                Node temp1 = userChildren.item(i);
                if (temp1.getNodeName().equals("userId")) {
                    int userIdTemp = Integer.parseInt(temp1.getTextContent().trim());
                    if (userIdTemp == userId) {
                        isCurrentUserId = true;
                    }
                }
                if (isCurrentUserId && temp1.getNodeName().equals("isAdmin")) {
                    boolean actStatus = Boolean.parseBoolean(temp1.getTextContent().trim());
                    if (actStatus == false) {
                        result = false;
                    }
                }
            }
            if (result == false) {
                return result;
            }
        }
        NodeList childNodes = node.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            boolean result = checkIsAdmin(userId, childNodes.item(i));
            if (result == false) {
                return result;
            }
        }
        return true;
    }

    public static boolean checkIsAdmin(int userId) {
        try {
            String userFilePath = FilePathHolder.getInstance().getUserXMLPath();
            Document doc = XMLUtils.parseDom(userFilePath);
            return checkIsAdmin(userId, doc);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(UserBO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(UserBO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(UserBO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }
}
